local brain = require "brains/musha_ghosthoundbrain"
local HOUND_NEAR_LEADER_DISTANCE = 20
local assets = {
	Asset("ANIM", "anim/musha_ghosthound.zip"),
	Asset("SOUND", "sound/hound.fsb")
}

local function ondeath(inst)
	SpawnPrefab("splash").Transform:SetPosition(inst:GetPosition():Get())
	inst.SoundEmitter:PlaySound("dontstarve/common/fireOut")
end

local function Retarget(inst)
	return FindEntity(
		inst,
		TUNING.HOUND_TARGET_DIST,
		function(guy)
			return guy.prefab ~= inst.prefab and guy.entity:IsVisible() and not guy.components.health:IsDead() and
				guy ~= (inst or inst.components.follower.leader) and
				not (not guy.components.follower or
					(guy.components.follower.leader and guy.components.follower.leader == inst.components.follower.leader)) and
				not guy:HasTag("player") and
				not guy:HasTag("companion") and
				not guy:HasTag("wall")
		end,
		{"_combat", "_health"},
		{"prey"}
	)
end

local function OnAttacked(inst, data)
	if data.attacker == inst.components.follower.leader then
		inst.components.combat:SetTarget(nil)
		inst.components.combat:GiveUp()
		return
	end
	inst.components.combat:SuggestTarget(data.attacker)
	inst.components.combat:ShareTarget(
		data.attacker,
		10,
		function(dude)
			return (dude:HasTag("musha_ghosthound") or
				dude.components.follower and dude.components.follower.leader == inst.components.follower.leader) and
				not dude.components.health:IsDead()
		end,
		6
	)

	if data and data.attacker and data.attacker.components.freezable then
		data.attacker.components.freezable:AddColdness(0.6)
		data.attacker.components.freezable:SpawnShatterFX()
	end
end

local function onclose(inst)
	if inst.components.follower:IsNearLeader(HOUND_NEAR_LEADER_DISTANCE) then
		inst.components.locomotor.runspeed = 10
	end
end

local function far(inst)
	if inst.components.follower:IsNearLeader(HOUND_NEAR_LEADER_DISTANCE) then
		inst.components.locomotor.runspeed = 18
		inst.components.combat:GiveUp()
	end
end

local function onusehound(inst, data)
	inst.Light:Enable(true)
	inst.SoundEmitter:PlaySound("dontstarve/common/gem_shatter")
	inst.components.sleeper:WakeUp()
	if not TheWorld.state.iswinter then
		inst.components.fueled:StartConsuming()
	end
end

local function offusehound(inst, data)
	inst.Light:Enable(false)
	inst.sg:GoToState("hit")
	inst.SoundEmitter:PlaySound("dontstarve/common/fireOut")
	inst.components.sleeper:GoToSleep()
	if not TheWorld.state.issummer then
		inst.components.fueled:StopConsuming()
	end
end

local function OnNewTarget(inst, data)
	local other = data.target
	if
		other and not other:HasTag("smashable") and inst.components.follower.leader and
			(other == inst.components.follower.leader or
				other.components.follower and other.components.follower.leader == inst.components.follower.leader)
	 then
		inst.components.combat:SetTarget(nil)
		inst.components.combat:GiveUp()
	end
end

local function fn()
	local inst = CreateEntity()
	inst.entity:AddTransform()
	inst.entity:AddAnimState()
	inst.entity:AddSoundEmitter()
	inst.entity:AddDynamicShadow()
	inst.entity:AddNetwork()

	--MakeCharacterPhysics(inst, 10, .5)
	MakeGhostPhysics(inst, 1, .5)
	RemovePhysicsColliders(inst)

	--inst.DynamicShadow:SetSize(2.5, 1.5)
	inst.Transform:SetFourFaced()

	inst:AddTag("scarytoprey")
	inst:AddTag("companion")
	inst:AddTag("notraptrigger")
	inst:AddTag("flying")
	inst:AddTag("noauradamage")
	inst:AddTag("musha_ghosthound")
	inst:AddTag("musha_follower")
	--[[ if inst.DLC2_fly then
		MakeAmphibiousCharacterPhysics(inst, 2, .5)
	end ]]
	inst.AnimState:SetBank("hound")
	inst.AnimState:SetBuild("musha_ghosthound")
	inst.AnimState:PlayAnimation("idle")

	local scale = math.random(45, 85) * 0.01
	inst.Transform:SetScale(scale, scale, scale)

	inst:AddComponent("colourtweener")
	inst.components.colourtweener:StartTween({1, 1, 1, .7}, 0)
	inst.entity:AddLight()
	inst.Light:SetRadius(.3)
	inst.Light:SetFalloff(.5)
	inst.Light:SetIntensity(.3)
	inst.Light:SetColour(50 / 255, 50 / 255, 50 / 255)
	--inst.Light:Enable(true)
	inst.AnimState:SetBloomEffectHandle("shaders/anim.ksh")
	inst:AddComponent("talker")
	inst.components.talker.fontsize = 22
	inst.components.talker.colour = Vector3(0.7, 1, 0.75, 1)

	inst.entity:SetPristine()
	if not TheWorld.ismastersim then
		return inst
	end

	inst:AddComponent("locomotor")
	inst.components.locomotor.pathcaps = {ignorecreep = true}
	inst.components.locomotor.runspeed = TUNING.HOUND_SPEED

	--inst:SetStateGraph("SGdogs")
	inst.sounds = {
		pant = "dontstarve/creatures/hound/pant",
		attack = "dontstarve/creatures/hound/attack",
		bite = "dontstarve/creatures/hound/bite",
		bark = "dontstarve/creatures/hound/bark",
		death = "dontstarve/creatures/hound/death",
		sleep = "dontstarve/creatures/hound/sleep",
		growl = "dontstarve/creatures/hound/growl",
		howl = "dontstarve/creatures/together/clayhound/howl",
		hurt = "dontstarve/creatures/hound/hurt"
	}
	inst:SetStateGraph("SGhound")

	inst:SetBrain(brain)

	inst:AddComponent("eater")
	inst.components.eater.PrefersToEat = function(self, food)
		if food.prefab == "ice" then
			return true
		else
			return false
		end
	end
	inst.components.eater:SetOnEatFn(
		function(inst, food)
			if food.prefab == "ice" then
				inst.components.fueled:DoDelta(25)
			end
		end
	)

	inst:AddComponent("follower")
	inst.components.follower:KeepLeaderOnAttacked()
	inst.components.follower.keepdeadleader = true
	inst:AddComponent("health")
	inst.components.health:SetMaxHealth(150)
	inst.components.health:StartRegen(1, 6)
	inst.components.health:SetAbsorptionAmount(0.5)
	inst:AddComponent("inspectable")
	inst:AddComponent("lootdropper")
	inst:AddComponent("playerprox")
	inst.components.playerprox:SetDist(9, 10)
	inst.components.playerprox:SetOnPlayerNear(onclose)
	inst.components.playerprox:SetOnPlayerFar(far)
	inst:DoTaskInTime(
		0,
		function(inst)
			if inst.components.follower.leader then
				inst.components.playerprox:SetTargetMode(
					inst.components.playerprox.TargetModes.SpecificPlayer,
					inst.components.follower.leader
				)
			end
		end
	)

	inst:AddComponent("combat")
	inst.components.combat:SetDefaultDamage(TUNING.HOUND_DAMAGE * 1.25)
	inst.components.combat:SetAttackPeriod(TUNING.ICEHOUND_ATTACK_PERIOD)
	inst.components.combat:SetRetargetFunction(1, Retarget)
	inst.components.combat.playerdamagepercent = 0

	inst:AddComponent("sleeper")
	inst.components.sleeper:SetResistance(5)

	inst:AddComponent("fueled")
	inst.components.fueled:InitializeFuelLevel(300)
	inst.components.fueled.rate = 1
	inst.components.fueled.accepting = false
	inst.components.fueled:SetDepletedFn(inst.components.health.Kill)
	inst.components.fueled:StopConsuming()

	inst:AddComponent("machine")
	inst.components.machine.turnonfn = onusehound
	inst.components.machine.turnofffn = offusehound
	inst.components.machine.cooldowntime = 0
	inst.components.machine:TurnOn()

	inst:ListenForEvent("newcombattarget", OnNewTarget)
	inst:ListenForEvent("death", ondeath)
	inst:ListenForEvent("attacked", OnAttacked)
	inst:ListenForEvent(
		"onhitother",
		function(inst, data)
			inst.components.fueled:DoDelta(5)
			inst.components.health:DoDelta(3)
			if data.target.components.freezable then
				data.target.components.freezable:AddColdness(0.2)
				data.target.components.freezable:SpawnShatterFX()
			end
			if data.target.components.burnable and data.target.components.burnable:IsBurning() then
				data.target.components.burnable:Extinguish()
			end
		end
	)
	inst:WatchWorldState(
		"season",
		function(inst, season)
			if season == SEASONS.WINTER and inst.components.machine.ison then
				inst.components.fueled:StopConsuming()
			elseif season == SEASONS.SPRING and inst.components.machine.ison then
				inst.components.fueled:StartConsuming()
			elseif season == SEASONS.SUMMER then
				inst.components.fueled:StartConsuming()
			end
		end
	)

	return inst
end

return Prefab("musha_ghosthound", fn, assets)
